<template>
    <div>
        子组件:
        <p>{{ requireID }}</p>
        <p>{{ tableData }}</p>
        <el-upload class="upload-demo" :limit="3" action="#" :show-file-list="true" :before-upload="handleBeforeUpload">
            <!-- <el-button type="primary" plain>选择用例</el-button> -->
            <template #trigger>
                <el-button type="primary">选择用例</el-button>
            </template>
            <el-button type="primary" @click="handleUploadFile">导入用例</el-button>
            <template #tip>
                <div class="el-upload__tip">
                    <p>文件不能超过2M。</p>
                    <p>{{ uploadTip }}</p>
                </div>
            </template>
        </el-upload>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import { postRequirementCase, getRequirementCase, postUploadCaseFile } from "@/api/project/index";
import { ElMessage } from "element-plus";

// 接收父组件传递的数据
const props = defineProps(["requireId", "tableData"]);

// 将父组件的参数转为响应式
const requireID = ref(props.requireId);
const tableCaseData = ref(props.tableData);


// 监听父组件数据
watchEffect(() => {
    requireID.value = props.requireId;
    tableCaseData.value = props.tableData;
    console.log(requireID.value, tableCaseData.value);
})

// 导入用例参数
const reqData = reactive({
    requirementId: requireID.value,
    filePath: ""
})

// 获取该需求的所有用例
const getAllTestList = async () => {
    console.log("获取所有用例");
    const resData = await getRequirementCase({
        id: requireID.value,
        page: 1,
        pageSize: 10
    });
    console.log(resData.data);
}

// 提示文字
const uploadTip = ref("");
// 临时保存要上传的文件
const fileList = ref<File>();
// 选择文件后临时保存
const handleBeforeUpload = async (file: any) => {
    console.log("上传之前的钩子函数");
    console.log(typeof file);
    fileList.value = file;
    uploadTip.value = file.name;
    if (fileList.value !== undefined) {
        const resData = await postUploadCaseFile(fileList.value);
        console.log(resData);
        if (resData.data.code == 7) {
            ElMessage.error(resData.data.msg);
            throw new Error(resData.data.msg);
        } /* else if (resData.data.msg == "文件已存在") {
            ElMessage.info(resData.data.msg);
            throw new Error(resData.data.msg);
        } */ else {
            reqData.filePath = resData.data.data.filePath;
            console.log(reqData);
            ElMessage.success(resData.data.msg);
        }

    } else {
        ElMessage.error("请选择要上传的文件");
        return;
    }
    return false;
}

// 开始上传文件
const handleUploadFile = async () => {
    console.log("开始上传");
    reqData.requirementId = requireID.value;
    const resData = await postRequirementCase(reqData);
    console.log(resData);
    fileList.value = undefined;
}

onMounted(() => {
    getAllTestList();
})

</script>

<style scoped lang="scss"></style>